# import wx
import numpy as np
import linecache
import os
import eventManager
# import myPanel


class Plot():

    def __init__(self, mypanel,eventManger):
        self.mypanel = mypanel
        self.__eventManager = eventManger
        self.dataSaveFile = "data.txt"
        self.axes_title = "Water Absorption Coefficient"
        self.axes_xlabel = "Wavelength (nm)"
        self.axes_ylabel = "Absorption Coefficient m(-1)"
        # self.MPL = myPanel.MPL_Panel(self)  # 调用自己建立的 panel 类
        # self.Figure = self.MPL.Figure
        # self.axes = self.MPL.axes
        # self.FigureCanvas = self.MPL.FigureCanvas

    def PlotCosX( self ):
        '''
        *  画一条曲线 cos(x)
        '''
        x = np.arange(-10,10,0.25)
        y = np.cos( x )
        self.mypanel.axes.clear()  # 清空上次画的内容
        self.mypanel.axes.set_title( self.axes_title )
        self.mypanel.axes.set_xlabel( self.axes_xlabel )
        self.mypanel.axes.set_ylabel( self.axes_ylabel )

        self.mypanel.axes.plot(x, y, 'b', linewidth=0.5 , label="d")
        self.mypanel.axes.legend()
        self.mypanel.axes.grid(True)
        self.mypanel.FigureCanvas.draw()

    def plotOne( self, data, color="blue" ):
        '''
        @ 根据数据画一条曲线
        @ 参数  data
        '''
        with open(self.dataSaveFile, 'r') as f:
            first_line = f.readline().strip('\n')
        x = first_line.split(';')
        x = np.array(x[1:]).astype(np.float)
        # x =np.array( self.wavelength ).astype(np.float)

        y = data.split(';')
        d = y[0]
        y =np.array(y[1:]).astype(np.float)

        self.mypanel.axes.clear()  # 清空上次画的内容
        self.mypanel.axes.set_title( self.axes_title )
        self.mypanel.axes.set_xlabel( self.axes_xlabel )
        self.mypanel.axes.set_ylabel( self.axes_ylabel )

        self.mypanel.axes.plot(x, y, color=color, linewidth=0.5 , label=d )
        self.mypanel.axes.legend()
        self.mypanel.axes.grid(True)
        self.mypanel.FigureCanvas.draw()  

    def Plot(self):
        """
        * 查看历史曲线
        * 默认从最后一条记录读取
        """
        last_line =  self.__get_last_line( self.dataSaveFile ).decode()
        self.plotOne( last_line )

    def OnPlot(self, e):
        """
        * 查看历史曲线
        * 默认从最后一条记录读取
        """
        last_line =  self.__get_last_line( self.dataSaveFile ).decode()
        self.plotOne( last_line )


    # def Plot( self ):
    #     '''
    #     * 根据数据画一条曲线
    #     '''
    #     with open(self.dataSaveFile, 'r') as f:
    #         first_line = f.readline().strip('\n')
    #     x = first_line.split(';')
    #     x = np.array(x[1:]).astype(np.float)
    #     # x =np.array( self.wavelength ).astype(np.float)

    #     y = data.split(';')
    #     d = y[0]
    #     y =np.array(y[1:]).astype(np.float)

    #     # print( x )
    #     # print( self.wavelength )
    #     # print( len(self.wavelength) )
    #     # print ( y )
    #     # print ( 'plotOne ----' )   
    #     # time.sleep(18)  
    #     # time.sleep(6)
    #     # x = np.arange(-10,10,0.25)
    #     # y = np.cos( x )
    #     self.mypanel.axes.clear()  # 清空上次画的内容
    #     self.mypanel.axes.set_title( 'Water Absorption Coefficient' )
    #     self.mypanel.axes.set_xlabel( 'Wavelength nm' )
    #     self.mypanel.axes.set_ylabel( 'Absorption Coefficient m(-1)' )

    #     self.mypanel.axes.plot(x, y, 'b', linewidth=0.5 , label=d )
    #     self.mypanel.axes.legend()
    #     self.mypanel.axes.grid(True)
    #     self.mypanel.FigureCanvas.draw()


     

    def plotSeven(self,data):
        '''
        * 根据数据画七条曲线
        * 兼容数量不够七条的
        '''        
        with open(self.dataSaveFile, 'r') as f:
            first_line = f.readline().strip('\n')
        x = first_line.split(';')
        x =np.array(x[1:]).astype(np.float)
        self.mypanel.axes.clear()  # 清空上次画的内容
        self.mypanel.axes.set_title( self.axes_title )
        self.mypanel.axes.set_xlabel( self.axes_xlabel )
        self.mypanel.axes.set_ylabel( self.axes_ylabel )

        if len(data) >=1 :
            y0 = data[0].split(';')
            d0 = y0[0]
            y0 =np.array(y0[1:]).astype(np.float)
            self.mypanel.axes.plot(x, y0, 'r', linewidth=0.5 , label = d0 )
        # len(data) =2 
        if len(data) >=2 :
            y1 = data[1].split(';')
            d1 = y1[0]
            y1 =np.array(y1[1:]).astype( np.float )
            self.mypanel.axes.plot(x, y1, color='orange', linewidth=0.5 , label=d1 )
        # len(data) =3 
        if len(data) >=3 :
            y2 = data[2].split(';')
            d2 = y2[0]
            y2 =np.array(y2[1:]).astype( np.float )
            self.mypanel.axes.plot(x, y2, 'y', linewidth=0.5 , label=d2 ) 
        # len(data) =4 
        if len(data) >=4 :
            y3 = data[3].split(';')
            d3 = y3[0]
            y3 =np.array(y3[1:]).astype( np.float )
            self.mypanel.axes.plot(x, y3, 'g', linewidth=0.5 , label=d3 ) 
        # len(data) =5 
        if len(data) >=5 :            
            y4 = data[4].split(';')
            d4 = y4[0]
            y4 =np.array(y4[1:]).astype(np.float)
            self.mypanel.axes.plot(x, y4, 'c', linewidth=0.5 , label=d4 ) 
        # len(data) =6 
        if len(data) >=6 :  
            y5 = data[5].split(';')
            d5 = y5[0]
            y5 =np.array(y5[1:]).astype( np.float )
            self.mypanel.axes.plot(x, y5, 'b', linewidth=0.5 , label=d5 ) 
        # len(data) =7 
        if len(data) >=6 :  
            y6 = data[6].split(';')
            d6 = y6[0]
            y6 =np.array(y6[1:]).astype( np.float )
            self.mypanel.axes.plot(x, y6,  color='purple', linewidth=0.5 , label=d6 )

        self.mypanel.axes.legend()
        self.mypanel.axes.grid( True )
        self.mypanel.FigureCanvas.draw()   

    # # def Plot(self):
    # #     """
    # #     * 查看历史曲线
    # #     * 默认从最后一条记录读取
    # #     """
    # #     last_line =  self.__get_last_line( self.dataSaveFile ).decode()
    # #     self.plotOne( last_line )

    # def OnPlot(self, e):
    #     """
    #     * 查看历史曲线
    #     * 默认从最后一条记录读取
    #     """
    #     # last_line =  self.__get_last_line( self.dataSaveFile ).decode()
    #     # self.plotOne( last_line )
    #     p = plot.Plot( mypanel = self.MPL  )
    #     p.Plot(   )

    def OnPlot_7(self, e):
        """
        最后间隔七条
        默认间隔数为1
        """
        result_line = []
        count = 0
        thefile = open( self.dataSaveFile, 'rb')
        while True:
            buffer = thefile.read(8192*1024)
            if not buffer:
                break
            count += buffer.count(b'\n')
        self.makeMsg(1, u" 文件共有 "+str(count)+" 行" ) 
        # self.statusBar.SetStatusText(u" 文件共有 "+str(count)+" 行",0)
        # 判断文件是否已有数据
        if count == 0:
            #print('文件没有内容！')
            self.makeMsg(2, u"数据文件没有记录！" ) 
            # with wx.MessageDialog(self,   u"数据文件没有记录！", u"错误提示", wx.OK )as dlg:
            #     dlg.ShowModal()
        elif count < 8:
            for i in range(count-1):
                result_line.append(linecache.getline( self.dataSaveFile, count-i))
        else:
            for i in range(7):
                result_line.append(linecache.getline( self.dataSaveFile, count-i))

        # 画7天的图像
        thefile.close()
        self.plotSeven( result_line )

    def OnPlot_D(self, e, interval, begin):
        """
        指定位置间隔七条
        考虑数据是否够
        """
        # print( "i am plot d")
        # self.readConfig()
        result_line = []
        count = 0
        thefile = open( self.dataSaveFile, 'rb')
        while True:
            buffer = thefile.read(8192*1024)
            if not buffer:
                break
            count += buffer.count(b'\n')
        self.makeMsg(1, u" 文件共有 "+str(count)+" 行" ) 
        
        # 判断文件绘图参数设置是否正确
        if count == 0:
            #print('文件没有内容！')
            self.makeMsg(2, u"数据文件没有记录！" ) 
            # with wx.MessageDialog(self,   u"数据文件没有记录！", u"错误提示", wx.OK )as dlg:
            #     dlg.ShowModal()
        elif ( interval*7 + begin ) < (count-1):
            for i in range(7):
                result_line.append( linecache.getline(  self.dataSaveFile,count-begin-i*interval ) )
        else:
            for i in range( ( (count-1)-begin )//interval ):
                result_line.append(linecache.getline(  self.dataSaveFile,count-begin-i*interval ) )

        # 画7天的图像 
        thefile.close()   
        self.plotSeven( result_line )

    def __get_last_line(self,filename):
        """
        get last line of a file
        :param filename: file name
        :return: last line or None for empty file
        """
        try:
            filesize = os.path.getsize(filename)
            if filesize == 0:
                return None
            else:
                with open(filename, 'rb') as fp: # to use seek from end, must use mode 'rb'
                    offset = -8                 # initialize offset
                    while -offset < filesize:   # offset cannot exceed file size
                        fp.seek(offset, 2)      # read # offset chars from eof(represent by number '2')
                        lines = fp.readlines()  # read from fp to eof
                        if len(lines) >= 2:     # if contains at least 2 lines
                            return lines[-1]    # then last line is totally included
                        else:
                            offset *= 2         # enlarge offset
                    fp.seek(0)
                    lines = fp.readlines()
                    return lines[-1]
        except FileNotFoundError:
            print(filename + ' not found!')
            return None

    def makeMsg(self,key,value):
        """
        事件对象：制造事件
        将事件写入event 并send
        """
        event = eventManager.Event( type_ = eventManager.EVENT_MSG)
        event.dict[key] = value

        # 发送事件
        self.__eventManager.SendEvent(event)

if __name__ == "__main__":
    pass
